package com.stud.framework.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import com.stud.common.jdbc.MyJdbcTemplate;
import com.stud.common.utils.spring.SpringUtils;
import com.stud.framework.config.properties.DruidProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Map;

/**
 * druid 配置多数据源
 *
 * @author Stud
 */
@Configuration
public class DruidConfig {
    @Bean(name = "masterDataSource")
    @ConfigurationProperties("spring.datasource.dynamic.datasource.master")
    @Primary
    public DataSource masterDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "slaveDataSource")
    @ConfigurationProperties("spring.datasource.dynamic.datasource.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.dynamic.datasource.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "masterJdbcTemplate")
    public MyJdbcTemplate masterJdbcTemplate(DruidProperties druidProperties) {
        MyJdbcTemplate jdbcTemplate = new MyJdbcTemplate();
        jdbcTemplate.setDataSource(masterDataSource(druidProperties));
        return jdbcTemplate;
    }

    @Primary
    @Bean(name = "masterTransactionManager")
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource masterDataSource) {
        DataSourceTransactionManager tm = new DataSourceTransactionManager(masterDataSource);
        tm.setNestedTransactionAllowed(true);
        return tm;
    }

    /**
     * 设置数据源
     *
     * @param targetDataSources 备选数据源集合
     * @param sourceName        数据源名称
     * @param beanName          bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) {
        try {
            DataSource dataSource = SpringUtils.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
        } catch (Exception ignored) {
        }
    }
}
